package com.xiaomaoguai.web.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * @Description :Post请求
 * @FileName: AbstractHttpClient.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年6月1日 下午2:32:19
 * @Version:V1.00
 */
public final class AdqHttpClientUtils {

	private static final Log LOG = LogFactory.getLog(AdqHttpClientUtils.class);

	public final static String APPLICATION_JSON_VALUE = "application/json";

	public final static String APPLICATION_XML_VALUE = "application/xml";

	private final static String USER_AGENT = "Mozilla/5.0";

	private static final HttpClient httpClient;

	private static final Header header;

	static {
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		httpClient = httpClientBuilder.build();
		header = new BasicHeader(HttpHeaders.USER_AGENT, USER_AGENT);
	}

	public static String doGetWithMapParam(String url, Map<String, String> params) {
		String result = null;
		if (StringUtils.isBlank(url)) {
			throw new IllegalArgumentException("URL is  needed!");
		}
		
		try {
			if (params != null && !params.isEmpty()) {
				List<NameValuePair> pairs = new ArrayList<>(params.size());
				for (Map.Entry<String, String> entry : params.entrySet()) {
					String value = entry.getValue();
					if (value != null) {
						pairs.add(new BasicNameValuePair(entry.getKey(), value));
					}
				}
				url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, "UTF-8"));
			}
			LOG.info("Request Url : " + url);
			HttpGet httpGet = new HttpGet(url);
			httpGet.addHeader(header);
			HttpResponse response = httpClient.execute(httpGet);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpGet.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
				LOG.info("执行结果： " + result);
			}
			EntityUtils.consume(entity);
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(StringUtils.isBlank(result) || result.equals("[]")){
			result = "{error:\"无返回数据\"}";
		}
		return result;
	}

	public static String doPost(String url, Map<String, String> params) {
		String result = null;
		if (StringUtils.isBlank(url)) {
			throw new IllegalArgumentException("URL is  needed!");
		}
		List<NameValuePair> pairs = null;
		if (params != null && !params.isEmpty()) {
			pairs = new ArrayList<>(params.size());
			for (Map.Entry<String, String> entry : params.entrySet()) {
				String value = entry.getValue();
				if (value != null) {
					pairs.add(new BasicNameValuePair(entry.getKey(), value));
				}
			}
		}
		try {
			HttpPost httpPost = new HttpPost(url);
			if (pairs != null && pairs.size() > 0) {
				httpPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));
			}
			httpPost.setHeader(header);
			HttpResponse response = httpClient.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				httpPost.abort();
				throw new RuntimeException("HttpClient,error status code :" + statusCode);
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity, "utf-8");
				LOG.info("执行结果： " + result);
			}
			EntityUtils.consume(entity);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(StringUtils.isBlank(result) || result.equals("[]")){
			result = "{error:\"无返回数据\"}";
		}
		return result;
	}
	
	public static void main(String[] args) {
		doGetWithMapParam("http://blog.csdn.net/zht666/article/details/8667811", 	new HashMap<String, String>() {

			private static final long serialVersionUID = 1L;

			{
				put("merchantNo", "123451234512345");
			}
		});
	}

}
